package com.mine.dubbo.netty.client;

import com.mine.dubbo.netty.DefaultFuture;
import com.mine.dubbo.netty.model.Request;
import com.mine.dubbo.netty.model.Response;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.experimental.Accessors;
import lombok.extern.log4j.Log4j2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Log4j2
@Accessors(chain = true)
public class Client {
    private ChannelFuture channelFuture;

    public Client() {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS));
                        ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                        ch.pipeline().addLast(new ObjectEncoder());
                        ch.pipeline().addLast(new ClientHandler());
                    }
                });
        try {
            channelFuture = b.connect("127.0.0.1", 8080).sync();
        } catch (InterruptedException e) {
            log.error("客户端创建失败了");
            e.printStackTrace();
        }
    }

    public Response send(Request request) {
        channelFuture.channel().writeAndFlush(request);
        log.info("发送请求成功");
        return new DefaultFuture(request).get();
    }

    public static void main(String[] args) {
        Client client = new Client();
        testSend(client);
    }

    public static void testSend(Client client) {
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    log.info("将要发送请求");
                    Response response = client.send(new Request(12, "123"));
                    log.info(response);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        executorService.shutdown();
    }
}
